from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from ..models.log import OperationLog

@login_required
def log_list(request):
    """
    操作日志列表视图
    仅允许校长角色访问，提供日志过滤和分页功能
    
    Args:
        request: HTTP请求对象
        
    Returns:
        HttpResponse: 渲染后的日志列表页面
    """
    # 检查用户权限，仅允许校长查看日志
    if request.session.get('CURRENT_ROLE') != 'principal':
        return render(request, 'error.html', {'message': '你没有权限访问日志管理页面'})
    
    # 获取过滤参数
    operation_type = request.GET.get('operation_type', '')
    content_type = request.GET.get('content_type', '')
    start_date = request.GET.get('start_date', '')
    end_date = request.GET.get('end_date', '')
    username = request.GET.get('username', '')
    
    # 基础查询集 - 使用select_related优化user字段查询
    logs = OperationLog.objects.select_related('user').order_by('-timestamp')
    
    # 应用过滤条件
    if operation_type:
        logs = logs.filter(operation_type=operation_type)
    if content_type:
        logs = logs.filter(content_type=content_type)
    if start_date:
        logs = logs.filter(timestamp__gte=start_date)
    if end_date:
        logs = logs.filter(timestamp__lte=end_date)
    if username:
        logs = logs.filter(user__username__icontains=username)
    
    # 分页处理
    paginator = Paginator(logs, 20)  # 每页20条记录
    page_number = request.GET.get('page')
    
    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        # 如果页码不是整数，返回第一页
        page_obj = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，返回最后一页
        page_obj = paginator.page(paginator.num_pages)
    
    # 获取所有操作类型和对象类型用于过滤选项
    # 使用缓存或在第一次查询时一起获取可以进一步优化
    operation_types = OperationLog.objects.values_list('operation_type', flat=True).distinct()
    content_types = OperationLog.objects.values_list('content_type', flat=True).distinct()
    
    context = {
        'page_obj': page_obj,          # 分页后的日志对象
        'operation_types': operation_types,  # 所有操作类型，用于过滤下拉框
        'content_types': content_types,      # 所有对象类型，用于过滤下拉框
        'current_filters': {
            'operation_type': operation_type,
            'content_type': content_type,
            'start_date': start_date,
            'end_date': end_date,
            'username': username
        }  # 当前应用的过滤条件，用于在模板中保持选中状态
    }
    
    return render(request, 'log/log_list.html', context)